<template>
  <div style="padding: 20px">
    <!-- 工作项筛选和操作栏 -->
    <div style="margin-bottom: 20px; display: flex; justify-content: space-between; align-items: center">
      <div style="display: flex; gap: 12px; align-items: center">
        <el-input
          v-model="searchForm.keyword"
          placeholder="搜索工作项标题或描述"
          style="width: 250px"
          clearable
          @input="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        
        <el-select v-model="searchForm.status" placeholder="状态" style="width: 120px" clearable @change="handleSearch">
          <el-option label="全部" value="" />
          <el-option label="打开" value="open" />
          <el-option label="进行中" value="in_progress" />
          <el-option label="已完成" value="completed" />
          <el-option label="关闭" value="closed" />
        </el-select>
        
        <el-select v-model="searchForm.type" placeholder="类型" style="width: 120px" clearable @change="handleSearch">
          <el-option label="全部" value="" />
          <el-option label="用户故事" value="story" />
          <el-option label="任务" value="task" />
          <el-option label="缺陷" value="bug" />
        </el-select>
        
        <el-select v-model="searchForm.assignee" placeholder="负责人" style="width: 120px" clearable @change="handleSearch">
          <el-option label="全部" value="" />
          <el-option
            v-for="member in projectMembers"
            :key="member.id"
            :label="member.name || member.username || member.realName"
            :value="member.id"
          />
        </el-select>
        
        <el-select v-model="searchForm.priority" placeholder="优先级" style="width: 120px" clearable @change="handleSearch">
          <el-option label="全部" value="" />
          <el-option label="高" value="high" />
          <el-option label="中" value="medium" />
          <el-option label="低" value="low" />
        </el-select>
        

      </div>
      
      <div style="display: flex; gap: 8px">
        <el-button @click="toggleView">
          <el-icon><Grid /></el-icon>
          {{ viewMode === 'workitems' ? '看板' : '工作项' }}
        </el-button>
        <el-button 
          v-if="isCurrentUserResponsible(null)" 
          type="primary" 
          @click="showTaskDialog = true"
        >
          <el-icon><Plus /></el-icon>
          新建工作项
        </el-button>
        <el-tooltip 
          v-else 
          content="只有项目成员才能新建工作项" 
          placement="top"
        >
          <el-button type="primary" disabled>
            <el-icon><Plus /></el-icon>
            新建工作项
          </el-button>
        </el-tooltip>
      </div>
    </div>


    <!-- 工作项列表视图 -->
    <div v-if="viewMode === 'workitems'">
      <el-table :data="filteredTasks" style="width: 100%" v-loading="loading" stripe>
        <el-table-column prop="number" label="编号" width="100" sortable>
          <template #default="{ row }">
            <el-link type="primary" @click="viewTask(row)">{{ row.number }}</el-link>
          </template>
        </el-table-column>
        <el-table-column prop="title" label="标题" min-width="250" show-overflow-tooltip>
          <template #default="{ row }">
            <div style="display: flex; align-items: center; gap: 8px">
              <el-tag :type="getTypeColor(row.type)" size="small">{{ getTypeLabel(row.type) }}</el-tag>
              <span>{{ row.title }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100" sortable>
          <template #default="{ row }">
            <el-tag :type="getStatusColor(row.status)" size="small">{{ getStatusLabel(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="assignee" label="负责人" width="120">
          <template #default="{ row }">
            <div v-if="row.assignee" style="display: flex; align-items: center; gap: 8px">
              <el-avatar :size="20" :src="getAssigneeAvatar(row.assignee)">{{ getAssigneeName(row.assignee) }}</el-avatar>
              <span>{{ getAssigneeName(row.assignee) }}</span>
            </div>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="priority" label="优先级" width="100" sortable>
          <template #default="{ row }">
            <el-tag :type="getPriorityColor(row.priority)" size="small">{{ getPriorityLabel(row.priority) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="startDate" label="开始时间" width="120" sortable>
          <template #default="{ row }">
            <span v-if="row.startDate">{{ formatDate(row.startDate) }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="endDate" label="结束时间" width="120" sortable>
          <template #default="{ row }">
            <span v-if="row.endDate">{{ formatDate(row.endDate) }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <div style="display: flex; gap: 8px; justify-content: flex-start; align-items: center;">
              <el-button size="small" @click="viewTask(row)" style="min-width: 50px;">查看</el-button>
              <el-button 
                v-if="isCurrentUserResponsible(row)" 
                size="small" 
                type="primary" 
                @click="editTask(row)" 
                style="min-width: 50px;"
              >编辑</el-button>
              <el-button 
                v-if="isCurrentUserResponsible(row)" 
                size="small" 
                type="danger" 
                @click="deleteTask(row)" 
                style="min-width: 50px;"
              >删除</el-button>
              <el-tag v-if="!isCurrentUserResponsible(row)" type="info" size="small">仅负责人可编辑</el-tag>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 看板视图 -->
    <div v-else class="kanban-view">
      <div class="kanban-columns">
        <div v-for="column in kanbanColumns" :key="column.status" class="kanban-column">
          <div class="column-header">
            <div class="column-title">
              <span>{{ column.title }}</span>
              <el-badge :value="getTasksByStatus(column.status).length" class="column-badge" />
            </div>
            <div class="column-actions">
              <el-dropdown trigger="click">
                <el-button text size="small">
                  <el-icon><MoreFilled /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="sortTasks(column.status, 'priority')">按优先级排序</el-dropdown-item>
                    <el-dropdown-item @click="sortTasks(column.status, 'createTime')">按创建时间排序</el-dropdown-item>
                    <el-dropdown-item @click="sortTasks(column.status, 'updateTime')">按更新时间排序</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </div>
          <div 
            class="column-content" 
            @dragover.prevent 
            @dragenter="handleDragEnter($event)"
            @dragleave="handleDragLeave($event)"
            @drop="handleDrop($event, column.status)"
          >
            <div
              v-for="task in getTasksByStatus(column.status)"
              :key="task.id"
              class="task-card"
              draggable="true"
              @dragstart="handleDragStart($event, task)"
              @click="viewTask(task)"
            >
              <div class="task-header">
                <div class="task-type">
                  <el-icon :style="{ color: getTypeColor(task.type) }">
                    <component :is="getTypeIcon(task.type)" />
                  </el-icon>
                  <span class="task-id">#{{ task.id }}</span>
                </div>
                <el-tag :type="getPriorityTagType(task.priority)" size="small">
                  {{ getPriorityText(task.priority) }}
                </el-tag>
              </div>
              <div class="task-title">{{ task.title }}</div>
              <div v-if="task.description" class="task-description">{{ task.description }}</div>
              <div class="task-footer">
                <div class="task-assignee">
                  <div v-if="task.assignee" style="display: flex; align-items: center; gap: 6px">
                    <el-avatar :size="20" :src="getAssigneeAvatar(task.assignee)">{{ getAssigneeName(task.assignee) }}</el-avatar>
                    <span>{{ getAssigneeName(task.assignee) }}</span>
                  </div>
                  <span v-else class="no-assignee">未分配</span>
                </div>
                <div v-if="task.endDate" class="task-due-date" :class="{ overdue: isOverdue(task.endDate) }">
                  {{ formatDate(task.endDate) }}
                </div>
              </div>
            </div>
            <div class="add-task-card" @click="addTaskToColumn(column.status)" v-if="isCurrentUserResponsible(null)">
              <el-icon><Plus /></el-icon>
              <span>添加工作项</span>
            </div>
            <div class="add-task-card disabled" v-else>
              <el-icon><Lock /></el-icon>
              <span>仅负责人可添加</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 新建/编辑工作项对话框 -->
    <el-dialog
      v-model="showTaskDialog"
      :title="editingTask ? '编辑工作项' : '新建工作项'"
      width="700px"
      @close="resetTaskForm"
    >
      <el-form ref="taskFormRef" :model="taskForm" :rules="taskRules" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="taskForm.title" placeholder="请输入工作项标题" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="taskForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入工作项描述"
          />
        </el-form-item>
        <el-row :gutter="16">
          <el-col :span="8">
            <el-form-item label="类型" prop="type">
              <el-select v-model="taskForm.type" placeholder="请选择类型" style="width: 100%">
                <el-option label="用户故事" value="story" />
                <el-option label="任务" value="task" />
                <el-option label="缺陷" value="bug" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="状态" prop="status">
              <el-select v-model="taskForm.status" placeholder="请选择状态" style="width: 100%">
                <el-option label="打开" value="open" />
                <el-option label="进行中" value="in_progress" />
                <el-option label="已完成" value="completed" />
                <el-option label="关闭" value="closed" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="优先级" prop="priority">
              <el-select v-model="taskForm.priority" placeholder="请选择优先级" style="width: 100%">
                <el-option label="低" value="low" />
                <el-option label="中" value="medium" />
                <el-option label="高" value="high" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="8">
            <el-form-item label="负责人" prop="assigneeId">
              <el-select v-model="taskForm.assigneeId" placeholder="请选择负责人" style="width: 100%" clearable>
                <el-option
                  v-for="member in projectMembers"
                  :key="member.id"
                  :label="member.name || member.username || member.realName"
                  :value="member.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="开始时间" prop="startDate">
              <el-date-picker
                v-model="taskForm.startDate"
                type="date"
                placeholder="请选择开始时间"
                style="width: 100%"
                @change="validateDateRange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="结束时间" prop="endDate">
              <el-date-picker
                v-model="taskForm.endDate"
                type="date"
                placeholder="请选择结束时间"
                style="width: 100%"
                @change="validateDateRange"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showTaskDialog = false">取消</el-button>
          <el-button type="primary" @click="saveTask" :loading="saving">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 工作项详情对话框 -->
    <el-dialog v-model="showTaskDetailDialog" title="工作项详情" width="700px">
      <div v-if="selectedTask">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="编号">{{ selectedTask.number }}</el-descriptions-item>
          <el-descriptions-item label="标题">{{ selectedTask.title }}</el-descriptions-item>
          <el-descriptions-item label="类型">
            <el-tag :type="getTypeColor(selectedTask.type)" size="small">{{ getTypeLabel(selectedTask.type) }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusColor(selectedTask.status)" size="small">{{ getStatusLabel(selectedTask.status) }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="优先级">
            <el-tag :type="getPriorityColor(selectedTask.priority)" size="small">{{ getPriorityLabel(selectedTask.priority) }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="负责人">
            <div v-if="selectedTask.assignee" style="display: flex; align-items: center; gap: 8px">
              <el-avatar :size="24" :src="getAssigneeAvatar(selectedTask.assignee)">{{ getAssigneeName(selectedTask.assignee) }}</el-avatar>
              <span>{{ getAssigneeName(selectedTask.assignee) }}</span>
            </div>
            <span v-else>未分配</span>
          </el-descriptions-item>
          <el-descriptions-item label="开始时间">
            <span v-if="selectedTask.startDate">{{ formatDate(selectedTask.startDate) }}</span>
            <span v-else>-</span>
          </el-descriptions-item>
          <el-descriptions-item label="结束时间">
            <span v-if="selectedTask.endDate">{{ formatDate(selectedTask.endDate) }}</span>
            <span v-else>-</span>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatDate(selectedTask.createTime) }}</el-descriptions-item>
          <el-descriptions-item label="更新时间">{{ formatDate(selectedTask.updateTime) }}</el-descriptions-item>
          <el-descriptions-item label="描述" :span="2">
            <p style="margin: 0; white-space: pre-wrap">{{ selectedTask.description || '无描述' }}</p>
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <div class="dialog-footer" style="display: flex; gap: 12px; justify-content: flex-end; align-items: center;">
          <el-button @click="showTaskDetailDialog = false">关闭</el-button>
          <el-button 
            v-if="isCurrentUserResponsible(selectedTask)" 
            type="primary" 
            @click="editTask(selectedTask)"
          >编辑</el-button>
          <el-button 
            v-if="isCurrentUserResponsible(selectedTask)" 
            type="danger" 
            @click="deleteTask(selectedTask)"
          >删除</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, nextTick, getCurrentInstance } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getAllWorkItems, getWorkItemsByProjectId, createWorkItem, updateWorkItem, deleteWorkItem } from '@/api/workitem'
import { getProjectMembers } from '@/api/project'
import request from '@/utils/request'

// 获取全局事件总线
const instance = getCurrentInstance()
const emitter = instance ? instance.proxy.emitter : null

const props = defineProps({
  projectId: {
    type: [String, Number],
    required: true
  }
})

// 响应式数据
const loading = ref(false)
const saving = ref(false)
const viewMode = ref('workitems') // 'workitems' | 'board'
const showTaskDialog = ref(false)
const showTaskDetailDialog = ref(false)
const editingTask = ref(null)
const selectedTask = ref(null)
const taskFormRef = ref()

// 搜索表单
const searchForm = ref({
  keyword: '',
  status: '',
  type: '',
  assignee: '',
  priority: ''
})

// 任务表单
const taskForm = reactive({
  title: '',
  description: '',
  type: 'task',
  status: 'open',
  priority: 'medium',
  assigneeId: '',
  startDate: '',
  endDate: ''
})

// 表单验证规则
const taskRules = {
  title: [{ required: true, message: '请输入任务标题', trigger: 'blur' }],
  type: [{ required: true, message: '请选择任务类型', trigger: 'change' }],
  priority: [{ required: true, message: '请选择优先级', trigger: 'change' }],
  startDate: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
  endDate: [{ required: true, message: '请选择结束时间', trigger: 'change' }]
}

// 项目成员
const projectMembers = ref([])

// 项目信息
const projectInfo = ref(null)

// 任务列表
const taskList = ref([])

// 加载项目信息
const loadProjectInfo = async () => {
  try {
    const response = await request.get(`/api/kanban/projects/${props.projectId}`)
    if (response.code === '200') {
      projectInfo.value = response.data
      // 只加载项目成员数据，loadProjectMembers内部会处理备选方案
      await loadProjectMembers()
    }
  } catch (error) {
    // 记录错误信息到控制台（非错误级别）
    console.info({
      message: '加载项目信息错误',
      error: error.message,
      timestamp: new Date().toISOString(),
      type: 'project_load_error'
    });

    // 处理不同类型的错误
    if (error.response) {
      // 服务器响应错误
      const status = error.response.status;
      const data = error.response.data;
      
      switch (status) {
        case 400:
          console.info('请求参数错误:', data.msg);
          break;
        case 401:
          console.info('身份验证失败，需要重新登录');
          break;
        case 403:
          console.info('权限不足，无法查看项目信息');
          break;
        case 404:
          console.info('项目不存在或已被删除');
          break;
        case 500:
          console.info('服务器内部错误');
          break;
        case 503:
          console.info('服务暂时不可用');
          break;
        default:
          console.info(`加载项目信息失败 (错误代码: ${status}):`, data.msg);
      }
    } else if (error.request) {
      // 网络错误
      if (error.code === 'ECONNABORTED') {
        console.info('请求超时，网络连接可能存在问题');
      } else if (error.message.includes('Network Error')) {
        console.info('网络连接失败');
      } else {
        console.info('网络请求失败');
      }
    } else {
      // 其他错误
      console.info('加载项目信息时发生未知错误');
    }
  }
}

// 加载小组成员数据
const loadGroupMembers = async (groupId) => {
  try {
    console.log('从小组加载成员，小组ID:', groupId)
    // 先获取小组的负责人列表
    const leadersResponse = await request.get('/api/leaders/byGroup', {
      params: { groupId }
    })
    
    if (leadersResponse.code === '200' && leadersResponse.data && leadersResponse.data.length > 0) {
      // 使用第一个负责人来获取该负责人的成员列表
      const firstLeader = leadersResponse.data[0]
      console.log('找到小组负责人:', firstLeader)
      
      const membersResponse = await request.get('/api/members/byLeader', {
        params: { leader: firstLeader.username || firstLeader.name }
      })
      
      if (membersResponse.code === '200') {
        console.log('负责人数据:', leadersResponse.data)
        console.log('成员数据:', membersResponse.data)
        
        // 只使用成员数据，不包含负责人
        let allMembers = []
        
        // 如果有成员数据，转换为对象格式
        if (membersResponse.data && membersResponse.data.length > 0) {
          // 成员数据可能是字符串数组，需要转换为对象
          allMembers = membersResponse.data.map(memberName => ({
            id: memberName,
            username: memberName,
            name: memberName,
            realName: memberName
          }))
        }
        
        // 如果没有成员数据，则使用负责人作为备选
        if (allMembers.length === 0) {
          allMembers = [...leadersResponse.data]
        }
        
        projectMembers.value = allMembers
        console.log('最终成员列表:', projectMembers.value)
        console.log('成员数量:', projectMembers.value.length)
      } else {
        // 如果获取成员失败，至少使用负责人列表
        projectMembers.value = leadersResponse.data
        console.log('使用负责人作为成员列表:', projectMembers.value)
      }
    } else {
      console.warn('获取小组负责人失败:', leadersResponse.msg)
      // 作为备选方案，尝试获取所有负责人
      await loadProjectLeaders(groupId)
    }
  } catch (error) {
    console.error('加载小组成员失败:', error)
    // 如果小组成员获取失败，尝试使用负责人API作为备选
    if (groupId) {
      await loadProjectLeaders(groupId)
    }
  }
}

// 加载项目负责人
const loadProjectLeaders = async (groupId) => {
  try {
    let response
    if (groupId) {
      // 如果有groupId，获取同一个group的用户作为可选负责人
      response = await request.get('/api/leaders/byGroup', {
        params: { groupId }
      })
    } else {
      // 否则获取所有负责人
      response = await request.get('/api/leaders')
    }

    if (response.code === '200') {
      // 将负责人数据合并到项目成员中，避免覆盖
      const leaders = (response.data || []).map(leader => ({
        ...leader,
        username: leader.username || leader.name || leader.realName // 确保有username字段
      }))
      // 如果项目成员为空，使用负责人数据作为备选
      if (projectMembers.value.length === 0) {
        projectMembers.value = leaders
      }
    } else {
      console.error('获取项目负责人失败:', response.msg)
    }
  } catch (error) {
    console.error('加载项目负责人失败:', error)
  }
}

// 加载项目成员数据
const loadProjectMembers = async () => {
  try {
    console.log('开始加载项目成员，项目ID:', props.projectId)
    const response = await getProjectMembers(props.projectId)
    console.log('项目成员API响应:', response)
    if (response.code === '200') {
      projectMembers.value = response.data || []
      console.log('设置项目成员列表:', projectMembers.value)
      
      // 如果项目成员为空，尝试从项目的小组信息中获取
      if (projectMembers.value.length === 0 && projectInfo.value?.groupId) {
        await loadGroupMembers(projectInfo.value.groupId)
      }
    } else {
      console.warn('获取项目成员失败:', response.msg)
      projectMembers.value = []
    }
  } catch (error) {
    console.error('加载项目成员失败:', error)
    projectMembers.value = []
  }
}

// 加载工作项数据
const loadWorkItems = async () => {
  loading.value = true
  try {
    const response = await getWorkItemsByProjectId(props.projectId)
    if (response.code === '200') {
      // 转换后端数据格式到前端格式
      taskList.value = response.data.map(item => ({
        id: item.workItemId,
        number: `WI-${String(item.workItemId).padStart(3, '0')}`,
        title: item.title,
        description: item.description,
        status: mapBackendStatusToFrontend(item.status),
        type: mapBackendCategoryToFrontend(item.category),
        priority: mapBackendPriorityToFrontend(item.priority),
        assignee: item.responsiblePerson,
        createTime: item.start_time ? formatDate(item.start_time) : null,
        updateTime: item.end_time ? formatDate(item.end_time) : null,
        startDate: item.start_time ? formatDate(item.start_time) : null,
        endDate: item.end_time ? formatDate(item.end_time) : null,
        projectId: item.projectId
      }))
    } else {
      ElMessage.error(response.msg || '获取工作项失败')
    }
  } catch (error) {
    console.error('加载工作项失败:', error)
    ElMessage.error('加载工作项失败')
  } finally {
    loading.value = false
  }
}

// 数据格式转换函数
const mapBackendStatusToFrontend = (status) => {
  const statusMap = {
    '准备做': 'open',
    '进行中': 'in_progress', 
    '已完成': 'completed',
    '已关闭': 'closed'
  }
  return statusMap[status] || 'open'
}

const mapBackendCategoryToFrontend = (category) => {
  const categoryMap = {
    '用户故事': 'story',
    '任务': 'task',
    '缺陷': 'bug'
  }
  return categoryMap[category] || 'task'
}

const mapBackendPriorityToFrontend = (priority) => {
  const priorityMap = {
    '高': 'high',
    '中': 'medium',
    '低': 'low'
  }
  return priorityMap[priority] || 'medium'
}

const getAssigneeByName = (name) => {
  const member = projectMembers.value.find(m => m.name === name)
  return member ? member.id : null
}

const formatDate = (dateStr) => {
  if (!dateStr) return ''
  return new Date(dateStr).toLocaleDateString('zh-CN')
}

// 看板列定义
const kanbanColumns = [
  { status: 'open', title: '打开', color: '#1890ff' },
  { status: 'in_progress', title: '进行中', color: '#52c41a' },
  { status: 'completed', title: '已完成', color: '#722ed1' },
  { status: 'closed', title: '关闭', color: '#999999' }
]

// 计算属性
const filteredTasks = computed(() => {
  let tasks = [...taskList.value]
  
  // 关键词筛选
  if (searchForm.value.keyword) {
    tasks = tasks.filter(task => 
      task.title.toLowerCase().includes(searchForm.value.keyword.toLowerCase()) ||
      (task.description && task.description.toLowerCase().includes(searchForm.value.keyword.toLowerCase()))
    )
  }
  
  // 状态筛选
  if (searchForm.value.status) {
    tasks = tasks.filter(task => task.status === searchForm.value.status)
  }
  
  // 类型筛选
  if (searchForm.value.type) {
    tasks = tasks.filter(task => task.type === searchForm.value.type)
  }
  
  // 负责人筛选
  if (searchForm.value.assignee) {
    const selectedMember = projectMembers.value.find(m => m.id == searchForm.value.assignee)
    if (selectedMember) {
      tasks = tasks.filter(task => task.assignee === selectedMember.name)
    }
  }
  
  // 优先级筛选
  if (searchForm.value.priority) {
    tasks = tasks.filter(task => task.priority === searchForm.value.priority)
  }

  // 排序
  if (searchForm.value.sortBy) {
    tasks.sort((a, b) => {
      const sortBy = searchForm.value.sortBy
      let aValue, bValue

      switch (sortBy) {
        case 'createTime':
        case 'updateTime':
        case 'startDate':
        case 'endDate':
          aValue = new Date(a[sortBy] || 0)
          bValue = new Date(b[sortBy] || 0)
          return bValue - aValue // 降序
        case 'priority':
          const priorityOrder = { 'high': 3, 'medium': 2, 'low': 1 }
          aValue = priorityOrder[a.priority] || 0
          bValue = priorityOrder[b.priority] || 0
          return bValue - aValue // 高优先级在前
        default:
          return 0
      }
    })
  }

  return tasks
})



// 方法
const handleSearch = () => {
  // 搜索逻辑已在计算属性中处理，这里可以添加额外的搜索逻辑
  // 例如：防抖处理、搜索历史记录等
}

const toggleView = () => {
  viewMode.value = viewMode.value === 'workitems' ? 'board' : 'workitems'
}

const sortTasks = (status, sortBy) => {
  // 实现按状态和字段排序的逻辑
  searchForm.value.sortBy = sortBy
  ElMessage.success(`已按${getSortByLabel(sortBy)}排序`)
}

// 获取排序字段的中文标签
const getSortByLabel = (sortBy) => {
  const labels = {
    'createTime': '创建时间',
    'updateTime': '更新时间',
    'startDate': '开始时间',
    'endDate': '结束时间',
    'priority': '优先级'
  }
  return labels[sortBy] || sortBy
}

const addTaskToColumn = (status) => {
  // 为指定状态列添加新任务
  Object.assign(taskForm, {
    title: '',
    description: '',
    type: 'task',
    status: status,
    priority: 'medium',
    assigneeId: '',
    startDate: '',
    endDate: ''
  })
  editingTask.value = null
  showTaskDialog.value = true
}

const getTasksByStatus = (status) => {
  return filteredTasks.value.filter(task => task.status === status)
}

// 拖拽相关函数
let draggedTask = null

const handleDragStart = (event, task) => {
  draggedTask = task
  // 设置拖拽数据
  event.dataTransfer.effectAllowed = 'move'
  event.dataTransfer.setData('text/plain', task.id)
  // 添加拖拽样式
  event.target.classList.add('dragging')
  
  // 延迟一点时间移除拖拽样式，以便在拖拽过程中看到效果
  setTimeout(() => {
    const cards = document.querySelectorAll('.task-card')
    cards.forEach(card => {
      if (card !== event.target) {
        card.style.opacity = '0.6'
      }
    })
  }, 10)
}

const handleDragEnter = (event) => {
  event.preventDefault()
  event.target.classList.add('drag-over')
}

const handleDragLeave = (event) => {
  event.preventDefault()
  event.target.classList.remove('drag-over')
}

const handleDrop = async (event, newStatus) => {
  event.preventDefault()
  
  // 移除所有列的拖拽样式
  const columns = document.querySelectorAll('.column-content')
  columns.forEach(column => {
    column.classList.remove('drag-over')
  })
  
  // 恢复所有任务卡片的样式
  const cards = document.querySelectorAll('.task-card')
  cards.forEach(card => {
    card.classList.remove('dragging')
    card.style.opacity = ''
  })
  
  // 如果没有拖拽任务或状态没有变化，则不处理
  if (!draggedTask || draggedTask.status === newStatus) {
    draggedTask = null
    return
  }
  
  // 保存原始状态，用于后续比较
  const oldStatus = draggedTask.status
  
  // 更新任务状态
  draggedTask.status = newStatus
  
  // 验证负责人信息
  if (!draggedTask.assignee) {
    ElMessage.error('任务缺少负责人信息，无法更新')
    return
  }
  
  // 准备更新数据
  const workItemData = {
    workItemId: draggedTask.id,
    title: draggedTask.title,
    description: draggedTask.description,
    category: mapFrontendCategoryToBackend(draggedTask.type),
    status: mapFrontendStatusToBackend(newStatus),
    priority: mapFrontendPriorityToBackend(draggedTask.priority),
    responsiblePerson: draggedTask.assignee,
    start_time: draggedTask.startDate ? new Date(draggedTask.startDate).toISOString() : null,
    end_time: draggedTask.endDate ? new Date(draggedTask.endDate).toISOString() : null,
    projectId: props.projectId
  }
  
  try {
    // 调用API更新任务
    const response = await updateWorkItem(draggedTask.id, workItemData)
    
    if (response.code === '200') {
      ElMessage.success('任务状态更新成功')
      
      // 对任何状态变更都触发全局事件
      if (emitter) {
        // 获取当前用户信息
        const currentUser = getCurrentUser();
        
        // 获取状态的中文名称
        const oldStatusText = getStatusLabel(oldStatus);
        const newStatusText = getStatusLabel(newStatus);

        // 构建变更描述 - 使用原...现...格式
        const changeDescription = `任务 #${draggedTask.id} "${draggedTask.title}" 状态：原[${oldStatusText}]现[${newStatusText}]`;

        // 触发任务状态变更事件
        emitter.emit('task-status-change', {
          id: draggedTask.id,
          title: draggedTask.title,
          description: changeDescription,
          status: newStatus,
          completedBy: newStatus === 'completed' ? (currentUser?.name || currentUser?.username || draggedTask.assignee || '未知用户') : '',
          user: currentUser // 传递当前用户信息
        })
      }
      
      // 重新加载任务列表
      await loadWorkItems()
    } else {
      // 如果更新失败，恢复原始状态
      draggedTask.status = oldStatus
      ElMessage.error(response.msg || '更新任务状态失败')
    }
  } catch (error) {
    // 如果发生错误，恢复原始状态
    draggedTask.status = oldStatus
    console.error('更新任务状态失败:', error)
    ElMessage.error('更新任务状态失败')
  } finally {
    // 清除拖拽任务
    draggedTask = null
  }
}

const viewTask = (task) => {
  selectedTask.value = task
  showTaskDetailDialog.value = true
}

const editTask = (task) => {
  editingTask.value = task
  // 通过assignee名称找到对应的成员ID
  const assigneeMember = projectMembers.value.find(m => m.username === task.assignee)
  Object.assign(taskForm, {
    title: task.title,
    description: task.description,
    type: task.type,
    status: task.status,
    priority: task.priority,
    assigneeId: assigneeMember?.id || '',
    startDate: task.startDate || '',
    endDate: task.endDate || ''
  })
  showTaskDialog.value = true
  showTaskDetailDialog.value = false
}

const duplicateTask = (task) => {
  // 通过assignee名称找到对应的成员ID
  const assigneeMember = projectMembers.value.find(m => m.username === task.assignee)
  Object.assign(taskForm, {
    title: `${task.title} (副本)`,
    description: task.description,
    type: task.type,
    priority: task.priority,
    assigneeId: assigneeMember?.id || '',
    dueDate: ''
  })
  editingTask.value = null
  showTaskDialog.value = true
}

const deleteTask = (task) => {
  ElMessageBox.confirm(
    `确定要删除任务 "${task.title}" 吗？`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      const response = await deleteWorkItem(task.id)
      if (response.code === '200') {
        ElMessage.success('任务删除成功')
        await loadWorkItems()
      } else {
        ElMessage.error(response.msg || '删除任务失败')
      }
    } catch (error) {
      console.error('删除任务失败:', error)
      ElMessage.error('删除任务失败')
    }
  }).catch(() => {
    // 用户取消删除
  })
}

const saveTask = async () => {
  taskFormRef.value.validate(async (valid) => {
    if (valid) {
      saving.value = true
      try {
        if (editingTask.value) {
          // 更新任务
          // 获取负责人用户名，确保不为空
          const responsiblePersonUsername = getAssigneeNameById(taskForm.assigneeId)
          if (!responsiblePersonUsername) {
            ElMessage.error('请选择有效的负责人')
            return
          }
          
          const workItemData = {
            workItemId: editingTask.value.id,
            title: taskForm.title,
            description: taskForm.description,
            category: mapFrontendCategoryToBackend(taskForm.type),
            status: mapFrontendStatusToBackend(taskForm.status),
            priority: mapFrontendPriorityToBackend(taskForm.priority),
            responsiblePerson: responsiblePersonUsername,
            start_time: taskForm.startDate ? new Date(taskForm.startDate).toISOString() : null,
            end_time: taskForm.endDate ? new Date(taskForm.endDate).toISOString() : null,
            projectId: props.projectId
          }
          
          const response = await updateWorkItem(editingTask.value.id, workItemData)
          if (response.code === '200') {
            ElMessage.success('任务更新成功')
            
            // 对任何任务更改都触发全局事件
            if (emitter) {
              // 获取当前用户信息
              const currentUser = getCurrentUser();
              
              // 构建变更描述 - 使用原...现...格式
              let changeDescription = `任务 #${editingTask.value.id} "${taskForm.title}"`;
              let hasChanges = false;

              // 标题变更
              if (editingTask.value.title !== taskForm.title) {
                changeDescription += ` 标题：原[${editingTask.value.title}]现[${taskForm.title}]`;
                hasChanges = true;
              }

              // 描述变更 - 由于描述可能很长，只显示变更状态
              if (editingTask.value.description !== taskForm.description) {
                changeDescription += ` 描述：已更新`;
                hasChanges = true;
              }

              // 状态变更
              if (editingTask.value.status !== taskForm.status) {
                const oldStatusText = getStatusLabel(editingTask.value.status);
                const newStatusText = getStatusLabel(taskForm.status);
                changeDescription += ` 状态：原[${oldStatusText}]现[${newStatusText}]`;
                hasChanges = true;
              }

              // 类型变更
              if (editingTask.value.type !== taskForm.type) {
                const oldTypeText = getTypeLabel(editingTask.value.type);
                const newTypeText = getTypeLabel(taskForm.type);
                changeDescription += ` 类型：原[${oldTypeText}]现[${newTypeText}]`;
                hasChanges = true;
              }

              // 优先级变更
              if (editingTask.value.priority !== taskForm.priority) {
                const oldPriorityText = getPriorityLabel(editingTask.value.priority);
                const newPriorityText = getPriorityLabel(taskForm.priority);
                changeDescription += ` 优先级：原[${oldPriorityText}]现[${newPriorityText}]`;
                hasChanges = true;
              }

              // 负责人变更
              const currentAssigneeName = getAssigneeNameById(taskForm.assigneeId);
              if (editingTask.value.assignee !== currentAssigneeName) {
                changeDescription += ` 负责人：原[${editingTask.value.assignee || '无'}]现[${currentAssigneeName || '无'}]`;
                hasChanges = true;
              }

              // 开始时间变更
              if (editingTask.value.startDate !== taskForm.startDate) {
                const oldStartDate = editingTask.value.startDate ? formatDate(editingTask.value.startDate) : '无';
                const newStartDate = taskForm.startDate ? formatDate(taskForm.startDate) : '无';
                changeDescription += ` 开始时间：原[${oldStartDate}]现[${newStartDate}]`;
                hasChanges = true;
              }

              // 结束时间变更
              if (editingTask.value.endDate !== taskForm.endDate) {
                const oldEndDate = editingTask.value.endDate ? formatDate(editingTask.value.endDate) : '无';
                const newEndDate = taskForm.endDate ? formatDate(taskForm.endDate) : '无';
                changeDescription += ` 结束时间：原[${oldEndDate}]现[${newEndDate}]`;
                hasChanges = true;
              }

              // 如果没有变更，添加默认描述
              if (!hasChanges) {
                changeDescription += ` 已更新`;
              }

              // 触发任务状态变更事件
              emitter.emit('task-status-change', {
                id: editingTask.value.id,
                title: taskForm.title,
                description: changeDescription,
                status: taskForm.status,
                completedBy: taskForm.status === 'completed' ? (currentUser?.name || currentUser?.username || getAssigneeNameById(taskForm.assigneeId) || '未知用户') : '',
                user: currentUser // 传递当前用户信息
              });
            }
            
            await loadWorkItems()
          } else {
            ElMessage.error(response.msg || '更新任务失败')
          }
        } else {
          // 新建任务
          // 获取负责人用户名，确保不为空
          const responsiblePersonUsername = getAssigneeNameById(taskForm.assigneeId)
          if (!responsiblePersonUsername) {
            ElMessage.error('请选择有效的负责人')
            return
          }
          
          const workItemData = {
            title: taskForm.title,
            description: taskForm.description,
            category: mapFrontendCategoryToBackend(taskForm.type),
            status: mapFrontendStatusToBackend(taskForm.status),
            priority: mapFrontendPriorityToBackend(taskForm.priority),
            responsiblePerson: responsiblePersonUsername,
            start_time: taskForm.startDate ? new Date(taskForm.startDate).toISOString() : null,
            end_time: taskForm.endDate ? new Date(taskForm.endDate).toISOString() : null,
            projectId: props.projectId
          }
          
          const response = await createWorkItem(workItemData)
          if (response.code === '200') {
            ElMessage.success('任务创建成功')

            // 对新创建的任务触发通知事件
            if (emitter) {
              // 获取当前用户信息
              const currentUser = getCurrentUser();

              // 触发任务创建事件
              emitter.emit('task-status-change', {
                id: response.data?.id || '新任务',
                title: taskForm.title,
                description: `新任务 "${taskForm.title}" 已创建`,
                status: taskForm.status,
                completedBy: taskForm.status === 'completed' ? (currentUser?.name || currentUser?.username || getAssigneeNameById(taskForm.assigneeId) || '未知用户') : '',
                user: currentUser // 传递当前用户信息
              });
            }

            await loadWorkItems()
          } else {
            ElMessage.error(response.msg || '创建任务失败')
          }
        }
        
        showTaskDialog.value = false
        resetTaskForm()
      } catch (error) {
        console.error('保存任务失败:', error)
        ElMessage.error('保存任务失败')
      } finally {
        saving.value = false
      }
    }
  })
}

// 前端到后端的数据格式转换
const mapFrontendStatusToBackend = (status) => {
  const statusMap = {
    'open': '准备做',
    'in_progress': '进行中',
    'completed': '已完成',
    'closed': '已关闭'
  }
  return statusMap[status] || '准备做'
}

const mapFrontendCategoryToBackend = (type) => {
  const typeMap = {
    'story': '用户故事',
    'task': '任务',
    'bug': '缺陷'
  }
  return typeMap[type] || '任务'
}

const mapFrontendPriorityToBackend = (priority) => {
  const priorityMap = {
    'high': '高',
    'medium': '中',
    'low': '低'
  }
  return priorityMap[priority] || '中'
}

const getAssigneeNameById = (id) => {
  const member = projectMembers.value.find(m => m.id == id)
  return member ? member.username : ''
}

const resetTaskForm = () => {
  editingTask.value = null
  Object.assign(taskForm, {
    title: '',
    description: '',
    type: 'task',
    status: 'open',
    priority: 'medium',
    assigneeId: '',
    startDate: '',
    endDate: ''
  })
  taskFormRef.value?.resetFields()
}

// 验证日期范围
const validateDateRange = () => {
  nextTick(() => {
    if (taskForm.startDate && taskForm.endDate) {
      const startDate = new Date(taskForm.startDate)
      const endDate = new Date(taskForm.endDate)
      
      if (startDate > endDate) {
        ElMessage.error('开始时间不能晚于结束时间，请重新选择！')
        // 清空结束时间
        taskForm.endDate = ''
      } else if (endDate < startDate) {
        ElMessage.error('结束时间不能早于开始时间，请重新选择！')
        // 清空开始时间
        taskForm.startDate = ''
      }
    }
  })
}

// 工具方法
const getStatusColor = (status) => {
  const statusMap = {
    open: 'info',
    in_progress: 'warning',
    completed: 'success',
    closed: 'info',
    not_started: 'info'
  }
  return statusMap[status] || 'info'
}

const getStatusLabel = (status) => {
  const statusMap = {
    open: '打开',
    in_progress: '进行中',
    completed: '已完成',
    closed: '关闭',
    not_started: '未开始'
  }
  return statusMap[status] || status
}

const getTypeColor = (type) => {
  const typeMap = {
    story: 'primary',
    task: 'success',
    bug: 'danger'
  }
  return typeMap[type] || 'info'
}

const getTypeLabel = (type) => {
  const typeMap = {
    story: '用户故事',
    task: '任务',
    bug: '缺陷'
  }
  return typeMap[type] || type
}

const getPriorityColor = (priority) => {
  const priorityMap = {
    low: 'info',
    medium: 'warning',
    high: 'danger'
  }
  return priorityMap[priority] || 'info'
}

const getPriorityTagType = (priority) => {
  const priorityMap = {
    low: 'info',
    medium: 'warning',
    high: 'danger'
  }
  return priorityMap[priority] || 'info'
}

const getPriorityText = (priority) => {
  const priorityMap = {
    low: '低',
    medium: '中',
    high: '高'
  }
  return priorityMap[priority] || priority
}

const getTypeIcon = (type) => {
  const iconMap = {
    story: 'User',
    task: 'List',
    bug: 'Warning'
  }
  return iconMap[type] || 'Document'
}

const getPriorityLabel = (priority) => {
  const priorityMap = {
    low: '低',
    medium: '中',
    high: '高'
  }
  return priorityMap[priority] || priority
}

const getAssigneeAvatar = (assigneeName) => {
  const member = projectMembers.value.find(m => m.username === assigneeName)
  return member?.avatar || ''
}

const getAssigneeName = (assigneeName) => {
  return assigneeName || ''
}

const copyTask = (task) => {
  // 通过assignee名称找到对应的成员ID
  const assigneeMember = projectMembers.value.find(m => m.username === task.assignee)
  Object.assign(taskForm, {
    title: `${task.title} (副本)`,
    description: task.description,
    type: task.type,
    priority: task.priority,
    assigneeId: assigneeMember?.id || '',
    dueDate: ''
  })
  editingTask.value = null
  showTaskDialog.value = true
}

const isOverdue = (dueDate) => {
  if (!dueDate) return false
  return new Date(dueDate) < new Date()
}

const formatDateTime = (datetime) => {
  return new Date(datetime).toLocaleString('zh-CN')
}

// 获取当前登录用户信息
const getCurrentUser = () => {
  try {
    const userInfo = JSON.parse(localStorage.getItem('system-user') || '{}')
    return userInfo
  } catch (error) {
    console.error('获取用户信息失败:', error)
    return {}
  }
}

// 判断当前用户是否是工作项的负责人
const isCurrentUserResponsible = (task) => {
  const currentUser = getCurrentUser()
  
  // 如果没有传入任务，则判断当前用户是否是项目成员
  if (!task) {
    // 检查当前用户是否在项目成员列表中
    return projectMembers.value.some(member => 
      member.username === currentUser.username || 
      member.name === currentUser.username ||
      member.username === currentUser.name || 
      member.name === currentUser.name
    )
  }
  
  // 如果传入了任务，则判断当前用户是否是该任务的负责人
  return currentUser && (currentUser.username === task.assignee || currentUser.name === task.assignee)
}

// 生命周期
onMounted(() => {
  loadProjectInfo()
  loadWorkItems()
})
</script>

<style scoped>


.kanban-view {
  background: #f5f5f5;
  border-radius: 8px;
  padding: 16px;
}

.add-task-card.disabled {
  background-color: #f5f5f5;
  color: #909399;
  cursor: not-allowed;
  border: 1px dashed #dcdfe6;
}

.kanban-columns {
  display: flex;
  gap: 20px;
  height: calc(100vh - 200px);
  overflow-x: auto;
  padding: 0 4px;
}

.kanban-column {
  flex: 1;
  min-width: 320px;
  max-width: 400px;
  background: #f8f9fa;
  border-radius: 8px;
  padding: 16px;
  border: 1px solid #e9ecef;
}

.column-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 2px solid #dee2e6;
}

.column-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  color: #495057;
}

.column-badge {
  background: #6c757d;
  color: white;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
  min-width: 20px;
  text-align: center;
}

.column-actions {
  opacity: 0.7;
  transition: opacity 0.2s;
}

.column-actions:hover {
  opacity: 1;
}

.column-content {
  display: flex;
  flex-direction: column;
  gap: 12px;
  max-height: calc(100vh - 300px);
  overflow-y: auto;
  padding: 16px;
  min-height: 400px;
}

.task-card {
  background: white;
  border: 1px solid #e9ecef;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 12px;
  cursor: pointer;
  transition: all 0.2s;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.08);
}

.task-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  transform: translateY(-2px);
  border-color: #1890ff;
}

.task-card.dragging {
  opacity: 0.5;
  transform: scale(0.95);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
}

.column-content.drag-over {
  background-color: rgba(64, 158, 255, 0.1);
  border: 2px dashed #409EFF;
}

.task-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 8px;
}

.task-meta {
  display: flex;
  align-items: center;
  gap: 8px;
}

.task-type {
  display: flex;
  align-items: center;
  gap: 4px;
}

.task-id {
  font-size: 12px;
  color: #6c757d;
  font-weight: 500;
  font-family: 'Monaco', 'Menlo', monospace;
}

.task-title {
  font-weight: 600;
  color: #212529;
  margin-bottom: 8px;
  line-height: 1.4;
  font-size: 14px;
}

.task-description {
  font-size: 12px;
  color: #6c757d;
  margin-bottom: 12px;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.task-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  margin-top: 12px;
}

.task-assignee {
  display: flex;
  align-items: center;
  gap: 6px;
  color: #495057;
}

.no-assignee {
  font-size: 12px;
  color: #999;
}

.task-dates {
  display: flex;
  flex-direction: column;
  gap: 4px;
  align-items: flex-end;
}

.date-item {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #6c757d;
  font-size: 11px;
}

.task-due-date {
  font-size: 12px;
  color: #666;
}

.task-due-date.overdue {
  color: #f5222d;
  font-weight: 500;
}

.add-task-card {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 16px;
  border: 2px dashed #dee2e6;
  border-radius: 8px;
  color: #6c757d;
  cursor: pointer;
  transition: all 0.2s;
  background: transparent;
}

.add-task-card:hover {
  border-color: #1890ff;
  color: #1890ff;
  background: #f0f8ff;
}

.task-detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.task-detail-title {
  display: flex;
  align-items: center;
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.task-detail-meta {
  display: flex;
  gap: 8px;
}

.task-description-content {
  background: #f8f9fa;
  padding: 16px;
  border-radius: 6px;
  color: #333;
  line-height: 1.6;
  white-space: pre-wrap;
}

/* 工作项列表样式优化 */
:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table th) {
  background-color: #f8f9fa;
  color: #495057;
  font-weight: 600;
}

:deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
  background-color: #f8f9fa;
}

:deep(.el-table__row:hover > td) {
  background-color: #e3f2fd !important;
}

/* 对话框样式优化 */
:deep(.el-dialog__header) {
  background-color: #f8f9fa;
  padding: 20px 24px 16px;
  border-bottom: 1px solid #dee2e6;
}

:deep(.el-dialog__title) {
  font-weight: 600;
  color: #212529;
}

:deep(.el-dialog__body) {
  padding: 24px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

:deep(.el-badge__content) {
  background-color: #1890ff;
}
</style>